package com.lbl.third.filter;

import com.alibaba.fastjson.JSON;
import com.lbl.third.common.BaseContext;
import com.lbl.third.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器.支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;


        //1.获取本次请求的URI
        String uri = request.getRequestURI();

        //定义不需要处理的路径
        String[] urls={
                "/employee/logout",
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //2判断此次请求是否需要处理，
        boolean check = Check(uri, urls);

        //3.如果为true则不需要处理，则直接放行
        if(check){
            filterChain.doFilter(request,response);
            return;
        }

        //4-1.判断登录状态，如果登录，则放行（服务端）
        if(request.getSession().getAttribute("employee")!=null){
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
//          Long id=Thread.currentThread().getId();
//            log.info("拦截线程id"+id);
            filterChain.doFilter(request,response);
            return;
        }
        //4-2.判断登录状态，如果登录，则放行(移动端)
        if(request.getSession().getAttribute("user")!=null){
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //5.如果未登录则返回登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param uri
     * @param urls
     * @return
     */
    public boolean Check(String uri,String[] urls){

        for (String url:urls) {
           if(PATH_MATCHER.match(url,uri)){
               return true;
           }
        }
        return false;
    }
}
